<template>
  <view class="page">
    <view class="header">
      <view class="logo">
        <image src="../../static/login/logo.png" />
      </view>
    </view>

    <view class="login">
      <view class="title"><text>欢迎登陆</text></view>

      <template>
        <view class="block">
          <view class="icon">
            <image src="/static/login/mobile.png" />
          </view>
          <view class="input">
            <input
              v-model="form_username"
              placeholder="请输入账号"
              type="text"
            />
          </view>
        </view>
        <view class="block">
          <view class="icon">
            <image src="/static/login/lock.png" />
          </view>
          <view class="input">
            <input
              v-model="form_password"
              placeholder="请输入密码"
              type="safe-password"
            />
          </view>
        </view>
      </template>

      <view class="button" @click="login()"><text>登录</text></view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form_username: "",
      form_password: "",
      form_tel: "",
      form_code: "",
      // 固定的账号密码
      validUsername: "admin",
      validPassword: "123456",
    };
  },
  onLoad() {
    // 检查是否已登录
    const isLogin = uni.getStorageSync("isLogin");
    if (isLogin) {
      // 已登录，直接跳转首页
      uni.reLaunch({
        url: "/pages/home/index",
      });
    }
  },
  methods: {
    login() {
      // 表单验证
      if (!this.form_username) {
        uni.showToast({
          title: "请输入账号",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      if (!this.form_password) {
        uni.showToast({
          title: "请输入密码",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      // 验证账号密码
      if (
        this.form_username === this.validUsername &&
        this.form_password === this.validPassword
      ) {
        // 登录成功
        uni.showToast({
          title: "登录成功",
          icon: "success",
          duration: 1500,
        });

        // 保存登录状态
        uni.setStorageSync("isLogin", true);
        uni.setStorageSync("username", this.form_username);

        // 延迟跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/home/index",
          });
        }, 1500);
      } else {
        // 登录失败
        uni.showToast({
          title: "账号或密码错误",
          icon: "none",
          duration: 2000,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
